package cn.stylefeng.guns.modular.gridsystem.controller;

import cn.hutool.core.date.DateUtil;
import cn.stylefeng.guns.core.pojo.page.PageResult;
import cn.stylefeng.guns.core.pojo.response.ResponseData;
import cn.stylefeng.guns.core.pojo.response.SuccessResponseData;
import cn.stylefeng.guns.modular.gridsystem.entity.BizUploadScore;
import cn.stylefeng.guns.modular.gridsystem.model.result.DeviceExceptionInfoResult;
import cn.stylefeng.guns.modular.gridsystem.model.result.ExceptionCountDataResult;
import cn.stylefeng.guns.modular.gridsystem.model.result.ExceptionHandleDataResult;
import cn.stylefeng.guns.modular.gridsystem.service.*;
import cn.stylefeng.guns.modular.gridsystem.utils.MyConst;
import cn.stylefeng.guns.modular.gridsystem.utils.MyFileUtils;
import lombok.extern.slf4j.Slf4j;
import net.aivoicetech.wav.WavFeatureDetect;
import net.aivoicetech.wav.entity.WavFeature;
import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.File;
import java.util.*;

/**
 * @author ssy
 * @date 2022/1/13 15:00
 */
@RestController
@Slf4j
public class HomeController {

    @Resource
    private BizStationService bizStationService;

    @Resource
    private BizGatewayService bizGatewayService;

    @Resource
    private BizGatewayChannelService bizGatewayChannelService;

    @Resource
    private BizExceptionService bizExceptionService;
    @Resource
    private BizUploadScoreService bizUploadScoreService;

    /**
     * 查询站点下的网关和设备列表
     * @param stationId
     * @return
     */
    @GetMapping("/index/getGatewayAndDeviceInfo")
    public ResponseData getGatewayAndDeviceInfo(Integer stationId){
        return new SuccessResponseData(bizStationService.getGatewayAndDeviceInfo(stationId));
    }

    /**
     * 上面的接口换成下面的接口
     * @param stationId
     * @return
     */
    @GetMapping("/index/getAllCount")
    public ResponseData getAllCount(Integer stationId){
        return new SuccessResponseData(bizStationService.getAllCount(stationId));
    }


    /**
     * 查询站点下的网关和设备列表-新
     * @param stationId
     * @return
     */
    @GetMapping("/index/getGatewayAndDeviceInfoNew")
    public ResponseData getGatewayAndDeviceInfoNew(Integer stationId){
        return new SuccessResponseData(bizStationService.getGatewayAndDeviceInfoNew(stationId));
    }

    /**
     * 当年月度故障数量
     * @param stationId
     * @return
     */
    @GetMapping("/index/getErrorCountByMonth")
    public ResponseData getErrorCountByMonth(Integer stationId) {

        int[] errCounts = new int[12];
        int[] processedCounts = new int[12];
        int[] unprocessedCounts = new int[12];
        int allErrCount = 0;
        int allProcessedCount = 0;

        List<ExceptionCountDataResult> resultList = bizExceptionService.getErrorCountByMonthList(stationId);

        for (ExceptionCountDataResult result:resultList){
            int index = result.getMonthDay() - 1;
            allErrCount += result.getErrCount();
            allProcessedCount += result.getProcessedNumber();
            errCounts[index] = result.getErrCount();
            processedCounts[index] = result.getProcessedNumber();
            unprocessedCounts[index] = result.getUnprocessedNumber();
        }

        Map<String, Object> map = new HashMap<>();
        map.put("errList",errCounts);
        map.put("processedList",processedCounts);
        map.put("unprocessedList",unprocessedCounts);
        map.put("allErrCount",allErrCount);
        map.put("allProcessedCount",allProcessedCount);
        return ResponseData.success(map);

    }


    /**
     * 获取设备最近7天的分数趋势图
     *
     * @param deviceId
     * @return
     */
    @GetMapping("/index/getExceptionLately")
    public ResponseData getExceptionLately(Integer deviceId) {
        List<BizUploadScore> list = bizUploadScoreService.getScoresLately(deviceId);
        Map<String, Object> map = new HashMap<>();
        List<String> xAxis = new ArrayList<>();
        List<String> yAxis = new ArrayList<>();
        for (BizUploadScore uploadScore : list) {
            String createdAt = DateUtil.formatDateTime(uploadScore.getCreatedAt());
            String score = uploadScore.getScore();
            xAxis.add(createdAt);
            yAxis.add(score);
        }
        map.put("xAxis", xAxis);
        map.put("yAxis", yAxis);
        return new SuccessResponseData(map);
    }

    /**
     * 获取站点中已处理未处理故障数量
     * @param stationId
     * @return
     */
    @GetMapping("/index/getExceptionHandleInfo")
    public ResponseData getExceptionHandleInfo(Integer stationId) {
        ExceptionHandleDataResult result = bizExceptionService.getExceptionHandleInfo(stationId);
        return ResponseData.success(result);
    }

    /**
     * 获取设备异常信息列表
     * @param deviceId
     * @return
     */
    @GetMapping("/index/getDeviceExceptionInfoList")
    public ResponseData getDeviceExceptionInfoList(Integer deviceId) {
        PageResult<DeviceExceptionInfoResult> result = bizExceptionService.getDeviceExceptionInfoList(deviceId);
        return ResponseData.success(result);
    }

    @PostMapping("/index/getBuffer")
    public ResponseData getBuffer(@RequestPart(value = "file") MultipartFile file) throws Exception {
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取文件后缀
        String prefix = null;
        if (fileName != null) {
            prefix = fileName.substring(fileName.lastIndexOf("."));
        }
        // 若须要防止生成的临时文件重复,能够在文件名后添加随机码
        File fileTemp = File.createTempFile(Objects.requireNonNull(fileName), prefix);
        FileUtils.copyInputStreamToFile(file.getInputStream(), fileTemp);
        WavFeatureDetect wavFeatureDetect = WavFeatureDetect.build(WavFeatureDetect.FeatureType.Spectrogram);
        List<WavFeature> feature = wavFeatureDetect.getFeature(fileTemp);
        return ResponseData.success(feature);
    }

    @PostMapping("/index/getBufferByPath")
    public ResponseData getBufferByPath(String fileName) throws Exception {
        String path = (MyFileUtils.getUploadPath() + fileName.replace("/upload", "")).trim().replaceAll("//", "/");
        File file = new File(path);
        if (!file.exists()) {
            return ResponseData.error(MyConst.FILE_NOT_EXIST);
        }
        WavFeatureDetect wavFeatureDetect = WavFeatureDetect.build(WavFeatureDetect.FeatureType.Spectrogram);
        List<WavFeature> feature = wavFeatureDetect.getFeature(file);
        return ResponseData.success(feature);
    }

    @PostMapping("/index/getData")
    public ResponseData getData(String fileName) throws Exception {
        String path = (MyFileUtils.getUploadPath() + fileName).trim().replaceAll("//", "/");
        File file = new File(path);
        if (!file.exists()) {
            return ResponseData.error(MyConst.FILE_NOT_EXIST);
        }
        WavFeatureDetect wavFeatureDetect = WavFeatureDetect.build(WavFeatureDetect.FeatureType.SoundWav, WavFeatureDetect.FeatureType.FREQUENCY, WavFeatureDetect.FeatureType.SoundPressLevel, WavFeatureDetect.FeatureType.Spectrogram);
        List<WavFeature> wavFeatureList = wavFeatureDetect.getFeature(file);
        ArrayList<Map<String, Object>> arrayList = new ArrayList<>();
        for (WavFeature wavFeature : wavFeatureList) {
            ArrayList data = (ArrayList) wavFeature.getData();
            final float stepTimeLength = wavFeature.getStepTimeLength();
            double[] subscript = new double[data.size()];
            if (wavFeature.getType().equals(WavFeatureDetect.FeatureType.SoundPressLevel.name())) {
                for (int j = 0; j < data.size(); j++) {
                    subscript[j] = Math.floor(((j * stepTimeLength)/1000)*10)/10;
                    data.set(j, Double.parseDouble(String.valueOf(data.get(j))) + 100);
                }
            }else if (wavFeature.getType().equals(WavFeatureDetect.FeatureType.Spectrogram.name())) {
                int[] data0 = (int[])data.get(0);
                subscript = new double[data0.length];
                for (int j = 0; j < data0.length; j++) {
                    subscript[j] = wavFeature.getSampleRate() / 2 / data0.length * (j + 1);
                    data.set(j,data0[j]);
                }
            } else {
                for (int j = 0; j < data.size(); j++) {
                    subscript[j] = Math.floor(((j * stepTimeLength)/1000)*10)/10;
                }
            }
            HashMap<String, Object> map = new HashMap<>();
            map.put("xData", subscript);
            map.put("yData", data);
            arrayList.add(map);

        }
        return ResponseData.success(arrayList);
    }

}
